﻿Imports System.Xml.Serialization
Imports System.Text.RegularExpressions

Public Class HostsConfig
    Inherits DefaultConfig
    Private Shared mConfigInfo As HostConfigInfo
    Private Shared mFileDateTime As DateTime

    Public Shared Property Hosts() As HostConfigInfo
        Get
            Return mConfigInfo
        End Get
        Set(ByVal value As HostConfigInfo)
            mConfigInfo = value
        End Set
    End Property

    Shared Sub New()
        mConfigInfo = CType(Load(ConfigFilePath), HostConfigInfo)
    End Sub

    Public Shared Function Load(ByVal fnPath As String) As IConfigInfo
        If mConfigInfo Is Nothing Then mConfigInfo = New HostConfigInfo
        Return LoadConfig(mFileDateTime, fnPath, mConfigInfo)
    End Function

    Public Overloads Shared ReadOnly Property ConfigFilePath() As String
        Get
            Dim Path As String = AppSettings("ConfigPath")
            If Not Path.EndsWith("/") Then Path = String.Concat(Path, "/")
            Return System.Web.HttpContext.Current.Server.MapPath(String.Format("{0}hosts.config", Path))
        End Get
    End Property

    Protected Overrides Sub Finalize()
        mConfigInfo = Nothing
        MyBase.Finalize()
    End Sub
End Class

<Serializable()> <XmlRoot("Hosts")> Public Class HostConfigInfo
    Implements IConfigInfo
    Private CurrentName As String

    Public DefaultPath As String

    <XmlElement("Site")> Public Items() As HostItem

    REM 查找数组
    Public Function Find(ByVal Name As String) As HostItem
        CurrentName = Name
        Return Array.Find(Items, AddressOf FindWhere)
    End Function

    Private Function FindWhere(ByVal item As HostItem) As Boolean
        Return Regex.IsMatch(CurrentName, String.Format("^{0}$", item.Host))
    End Function
End Class


<Serializable()> Public Class HostItem
    Public Host As String
    Public Path As String
    Public Aspx As String
    Public DSN As String
End Class

